//
//  Chapter2ViewController.m
//  OpenGLES_Learning
//
//  Created by Mac Center on 7/26/13.
//  Copyright (c) 2013 Mac Center. All rights reserved.
//

#import "Chapter2ViewController.h"


typedef struct {
    GLKVector3  positionCoords;
}sceneVertex;

static const sceneVertex vertexs[] = {
    {{-0.5, -0.5, 0}},
    {{0.5, -0.5, 0}},
    {{-0.5, 0.5, 0}}
};

@interface Chapter2ViewController ()

@end

@implementation Chapter2ViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    GLKView    *glView = (GLKView*)self.view;
    NSAssert([glView isKindOfClass:[GLKView class]], @"View controller's view is not a GLKView" );
    glView.context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
    [EAGLContext setCurrentContext:glView.context];
    
    self.baseEffect = [[GLKBaseEffect alloc] init];
    self.baseEffect.useConstantColor =  GL_TRUE;
    self.baseEffect.constantColor = GLKVector4Make(1.0, 1.0, 1.0, 1.0);
    
    glClearColor(0.0, 0.0, 0.0, 0.0);
    glGenBuffers(1, &vertextBufferID);
    glBindBuffer(GL_ARRAY_BUFFER, vertextBufferID);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertexs), vertexs, GL_STATIC_DRAW);
    
    
}

- (void)viewDidUnload {
    [super viewDidUnload];
    
    GLKView *v = (GLKView *)self.view;
    [EAGLContext setCurrentContext:v.context];
    
    if (vertextBufferID != 0) {
        glDeleteBuffers(1, &vertextBufferID);
        vertextBufferID = 0;
    }
    v.context = nil;
    [EAGLContext setCurrentContext:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)glkView:(GLKView *)view drawInRect:(CGRect)rect {
    [self.baseEffect prepareToDraw];
    glClear(GL_COLOR_BUFFER_BIT);
    glEnableVertexAttribArray(GLKVertexAttribPosition);
    glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, sizeof(sceneVertex), NULL);
    glDrawArrays(GL_TRIANGLES, 0, 3);
}
@end
